package config

import (
	"fmt"

	"github.com/spf13/viper"
)

// ServerConfig 服务器配置
var ServerConfig struct {
	Mode      string
	Port      int
	JWTSecret string
	JWTExpire int
}

// DBConfig 数据库配置
var DBConfig struct {
	Type         string
	Host         string
	Port         int
	DBName       string
	Username     string
	Password     string
	MaxIdleConns int
	MaxOpenConns int
	LogMode      bool
}

// RedisConfig Redis配置
var RedisConfig struct {
	Enable   bool
	Host     string
	Port     int
	Password string
	DB       int
}

// LogConfig 日志配置
var LogConfig struct {
	Level      string
	Format     string
	OutputPath string
	MaxSize    int
	MaxAge     int
	MaxBackups int
}

// InitConfig 初始化配置
func InitConfig(configPath string) error {
	viper.SetConfigName("config")
	viper.SetConfigType("yaml")
	viper.AddConfigPath(configPath)

	if err := viper.ReadInConfig(); err != nil {
		return fmt.Errorf("failed to read config file: %w", err)
	}

	// 加载服务器配置
	ServerConfig.Mode = viper.GetString("server.mode")
	ServerConfig.Port = viper.GetInt("server.port")
	ServerConfig.JWTSecret = viper.GetString("server.jwt_secret")
	ServerConfig.JWTExpire = viper.GetInt("server.jwt_expire")

	// 加载数据库配置
	DBConfig.Type = viper.GetString("database.type")
	DBConfig.Host = viper.GetString("database.host")
	DBConfig.Port = viper.GetInt("database.port")
	DBConfig.DBName = viper.GetString("database.dbname")
	DBConfig.Username = viper.GetString("database.username")
	DBConfig.Password = viper.GetString("database.password")
	DBConfig.MaxIdleConns = viper.GetInt("database.max_idle_conns")
	DBConfig.MaxOpenConns = viper.GetInt("database.max_open_conns")
	DBConfig.LogMode = viper.GetBool("database.log_mode")

	// 加载Redis配置
	RedisConfig.Enable = viper.GetBool("redis.enable")
	RedisConfig.Host = viper.GetString("redis.host")
	RedisConfig.Port = viper.GetInt("redis.port")
	RedisConfig.Password = viper.GetString("redis.password")
	RedisConfig.DB = viper.GetInt("redis.db")

	// 加载日志配置
	LogConfig.Level = viper.GetString("log.level")
	LogConfig.Format = viper.GetString("log.format")
	LogConfig.OutputPath = viper.GetString("log.output_path")
	LogConfig.MaxSize = viper.GetInt("log.max_size")
	LogConfig.MaxAge = viper.GetInt("log.max_age")
	LogConfig.MaxBackups = viper.GetInt("log.max_backups")

	return nil
}
